package com.mrd.shiptask_shipowner.unit_tools;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.loopj.android.http.PersistentCookieStore;
import com.mrd.shiptask_shipowner.constants.HttpConstant;
import com.mrd.shiptask_shipowner.shiareutil.SharePreferenceUtil;

import android.content.Context;

public class HttpUtil {
	private static final int SO_TIMEOUT = 60000;
	private static final int CONNECTION_TIMEOUT = 30000;
	private static String USER_AGENT = "Android";
	private static CookieStore cookieStore = null;

	/**
	 * 以传统模式提交数据
	 * 
	 * @param url
	 * @param entity
	 * @return
	 */
	public static String doPost(String url, HttpEntity entity, Context ctx) {
		HttpPost request = new HttpPost(url);
		request.setEntity(entity);
		return doPostWithCookie(request, ctx);
	}

	/**
	 * 以ajax的形式提交数据
	 * 
	 * @param url
	 * @param entity
	 * @return
	 */
	public static String doAjaxPost(String url, HttpEntity entity, Context ctx) {
		HttpPost request = new HttpPost(url);
		request.setHeader("Content-Type",
				"application/x-www-form-urlencoded; charset=utf-8");
		request.setEntity(entity);
		return doPostWithCookie(request, ctx);
	}

	/**
	 * 附加cookie提交数据
	 * 
	 * @param request
	 * @return
	 */
	public static String doPostWithCookie(HttpUriRequest request, Context ctx) {
		String result = null;
		HttpParams httpParams = new BasicHttpParams();
		try {
			try {
				HttpProtocolParams.setUserAgent(httpParams, USER_AGENT);
				DefaultHttpClient dhc = new DefaultHttpClient(httpParams);
				dhc.setCookieStore(cookieStore);
				HttpConnectionParams.setConnectionTimeout(httpParams,
						CONNECTION_TIMEOUT);
				HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
				dhc.setParams(httpParams);
				HttpResponse response = null;
				response = dhc.execute(request);
				if (response.getStatusLine().getStatusCode() == 200) {
					cookieStore = dhc.getCookieStore();
					result = EntityUtils
							.toString(response.getEntity(), "UTF-8");
					/* 获取并保存Cookie值 */
					PersistentCookieStore myCookieStore = new PersistentCookieStore(
							ctx);
					List<Cookie> cookies = dhc.getCookieStore().getCookies();
					for (Cookie cookie : cookies) {
						myCookieStore.addCookie(cookie);
					}
					myCookieStore.getCookies();
				} else if (response.getStatusLine().getStatusCode() == 404) {
					result = "网络地址不存在，请联系管理人员处理。。。";
				} else if (response.getStatusLine().getStatusCode() == 503) {
					result = "系统异常，请退出登陆后再重试。。。";
				}
				if (request.isAborted()) {
					request.abort();
				}
				return result;
			} catch (SocketTimeoutException e) {
				return HttpConstant.NETWORK_UNAVAILABLE;
			} catch (ConnectTimeoutException e) {

				return HttpConstant.TIME_OUT_EXCEPTION;
			} catch (ClientProtocolException e) {
				e.printStackTrace();
				result = HttpConstant.NETWORK_UNAVAILABLE;
				return result;
			} catch (IOException e) {
				e.printStackTrace();
				result = HttpConstant.NETWORK_UNAVAILABLE;
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = HttpConstant.NETWORK_UNAVAILABLE;
		}
		return result;
	}

	/**
	 * 通过url发送post请求，返回请求结果
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	public static StringBuffer queryStringForPost(String url,
			Map<String, Object> params, Context ctx) {
		try {
			List<NameValuePair> msg = new ArrayList<NameValuePair>();
			JSONObject jobj = new JSONObject();
			for (String key : params.keySet()) {
				jobj.put(key, params.get(key));
			}
			msg.add(new BasicNameValuePair("params", jobj.toString()));
			HttpEntity entity = new UrlEncodedFormEntity(msg, HTTP.UTF_8);

			return new StringBuffer(doAjaxPost(url, entity, ctx));
		} catch (JSONException e) {
		} catch (UnsupportedEncodingException e) {
		}
		return null;
	}

	/**
	 * 提交参数里有文件的数据
	 * 
	 * @param url
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public static StringBuffer uploadPictureUtil(Context ctx, String url,
			File file) throws Exception {
		MultipartEntity entity = new MultipartEntity();
		// 添加文件参数
		if (file != null && file.exists()) {
			entity.addPart("file", new FileBody(file));
		}
		return new StringBuffer(doPost(url, entity, ctx));
	}

	/**
	 * 用户登录验证
	 * 
	 * @param username
	 * @param pwd
	 * @param ac
	 * @return successFlag = "1"
	 * @throws Exception
	 */
	public static String login(String account, String pwd, Context ac)
			throws Exception {
		SharePreferenceUtil sp = new SharePreferenceUtil(ac, "saveUser");

		if (FunctionOfActivity.isNetworkAvailable(ac)) {
			String httpUrl = HttpUrlConstant.BASE_URL
					+ HttpUrlConstant.LOGIN_URL;
			JSONObject jobj = new JSONObject();
			jobj.put("account", account);
			jobj.put("password", pwd);
			jobj.put("deviceuuid", FunctionOfActivity.getDeviceId(ac));
			List<NameValuePair> msg = new ArrayList<NameValuePair>();
			msg.add(new BasicNameValuePair(HttpConstant.TAG_PARAM, jobj
					.toString()));
			String strResult = queryStringForPostOfLogin(httpUrl, msg);
			if (null == strResult || "".equals(strResult)
					|| HttpConstant.NETWORK_UNAVAILABLE.equals(strResult)) {
				return "服务器异常。";
			}
			JSONObject obj = new JSONObject(strResult);
			String isactive = obj.getString(HttpConstant.ACCOUNT_ISACTIVE);
			if (HttpConstant.ACCOUNT_ACTIVE.equals(isactive)) {
				String ispass = obj.getString(HttpConstant.MATCH_ISPASS);
				if (HttpConstant.MATCH_PASS.equals(ispass)) {
					String shipname = obj
							.getString(HttpConstant.PARAM_SHIP_NAME);
					String ship_id = obj.getString(HttpConstant.PARAM_SHIP_ID);
					sp.setId(account);
					sp.setPasswd(EncrUtil.encrypt(pwd));
					sp.setShip_name(shipname);
					sp.setShip_id(ship_id);
					return HttpConstant.MATCH_PASS;
				} else if (HttpConstant.MATCH_NOTPASS.equals(ispass)) {
					return "提示：密码错误。";
				} else if (HttpConstant.DEVICE_ALREADY_LOGIN.equals(ispass)) {
					return "提示：该帐号已在其他终端激活，目前不能在您的设备登录，如有疑问请联系管理人员。";
				}
			} else if (HttpConstant.ACCOUNT_DISACTIVE.equals(isactive)) {
				return "提示：账号未激活。";
			}
		} else if (!FunctionOfActivity.isNetworkAvailable(ac)) {
			return ("网络未打开，无法连接服务器。");
		}
		return "系统异常，请重新登录";
	}

	// 通过url发送post请求，返回请求结果
	@SuppressWarnings("unchecked")
	public static String queryStringForPostOfLogin(String url,
			@SuppressWarnings("rawtypes") List msg) {
		HttpPost request = new HttpPost(url);
		String result = null;
		try {
			request.setHeader("Content-Type",
					"application/x-www-form-urlencoded; charset=utf-8");
			request.setEntity(new UrlEncodedFormEntity(msg, HTTP.UTF_8));
			DefaultHttpClient dhc = new DefaultHttpClient();
			dhc.getParams().setParameter(
					CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
			HttpResponse response = dhc.execute(request);
			System.out.println(url + "**queryStringForPost:"
					+ response.getStatusLine().getStatusCode());
			if (response.getStatusLine().getStatusCode() == 200) {
				result = EntityUtils.toString(response.getEntity());
				return result;
			}
		} catch (ClientProtocolException e) {
			e.getStackTrace();
			result = HttpConstant.NETWORK_UNAVAILABLE;
			return result;
		} catch (IOException e) {
			e.printStackTrace();
			result = HttpConstant.NETWORK_UNAVAILABLE;
			return result;
		}
		return result;
	}

}
